<template>
	<view class="panel-root flex justify-start align-center">
		<view @tap="clickMask" class="mask-board">
		</view>
		<view class="flex justify-center align-center shadow-blur bg-white input-bar padding-left padding-right"
			:style="'bottom:'+inputBarBottom+'px;'">
			<view class="flex justify-end align-center padding" style="width: 100%;">
				<view class="flex justify-center align-center" style="width: 95%;">
					<text class="text-black text-lg">{{title}}</text>
				</view>
				<view class="text-bold text-gray text-xl" style="width: 5%;">
					<text @tap="clickMask" class="cuIcon-close"></text>
				</view>
			</view>
			<view v-if="useAudio&&audioPath&&audioPath.length>0" class="flex justify-start align-center"
				style="width: 100%;">
				<view class="text-xl text-bold text-gray">
					<text @tap="deleteAudio" class="cuIcon-delete"></text>
				</view>
				<view class="padding" style="width: 75%;">
					<audio-player :initDuration="duration" @onGetDuration="onGetAudioDuration" v-if="audioPath!==null" :src="audioPath">
					</audio-player>
				</view>
				<view class="flex justify-start align-center">
					<view class="padding-left cu-load load-cuIcon"
						:class="requestStatus.isAudioUploading?'loading':'over'"></view>
					<view v-if="requestStatus.isAudioUploading">
						<text class="padding-left-xs text-grey text-sm">上传中</text>
					</view>
					<view v-if="audioPath.length>0&&requestStatus.isAudioUploading==false">
						<text
							class="padding-left-xs text-grey text-sm">{{requestStatus.isAudioUploadSuccess?'上传成功':'上传失败'}}</text>
					</view>
				</view>
			</view>
			<view class="input-area flex justify-center align-center">
				<textarea :show-confirm-bar="false" :adjust-position="false" v-if="useAudio==false" v-model="content"
					maxlength="-1" class="text-black" :focus="foucs" :auto-focus="autoFocus" @blur="showMask=false"
					@focus="onTextInputFocus" @input="contentUpdate"
					:placeholder="originInfo.replyUser!==null&&originInfo.replyUser.length>0?'回复@'+originInfo.replyUser:'都让一让,听我说两句>_<'"
					style="width: 100%;height: 100%;"></textarea>
				<view v-else class="flex justify-center align-center bg-white shadow-warp"
					style="flex-direction: column;width: 100%;height: 150upx;">
					<view class="flex justify-center align-center padding-bottom-xs" style="width: 100%;">
						<text v-if="isStart==false" class="text-df text-black">点击开始录音</text>
						<text v-else class="text-df text-black">{{format(showDuration)}}</text>
					</view>
					<view class="flex justify-around align-center" style="width: 100%;">
						<view @tap="reStart" class="flex justify-center align-center" style="flex-direction: column;">
							<view class="round line-gray text-xl"><text class="cuIcon-refresh"></text></view>
							<text class="text-grey">重录</text>
						</view>
						<view @tap="startRecord" class="bg-gray round flex justify-center align-center"
							style="width: 100upx;height: 100upx;">
							<view class="bg-gradual-orange round flex justify-center align-center"
								style="width: 90upx;height: 90upx;">
								<view class="text-xl">
									<text :class="'text-white cuIcon-'+recordIcon"></text>
								</view>
							</view>
						</view>
						<view @tap="saveAction" class="flex justify-center align-center"
							style="flex-direction: column;">
							<view class="round line-gray text-xl"><text class="cuIcon-check"></text></view>
							<text class="text-grey">保存</text>
						</view>
					</view>
				</view>
			</view>
			<view class="flex justify-start padding-top-sm padding-bottom-sm" style="flex-wrap: wrap;width: 100%;">
				<view v-for="(item,index) in atUserList" :key="index">
					<view class="padding-left-sm padding-top-sm">
						<view @tap="jumpToUserProfile(item.user_id)" class="round cu-tag text-blue"
							style="background-color: #eff6fb;">
							@{{item.nickname}}
						</view>
					</view>
				</view>
			</view>
			<view v-if="imgList.length>0" class="padding-top-sm" style="width: 80%;">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage"
						:data-url="item.local">
						<image :class="(item.is_uping==false&&item.remote==null)||(item.is_uping==true)?'bg-mask':''"
							:src="item.local" mode="aspectFill"></image>
						<view class="cu-load load-cuIcon text-white padding-top"
							:class="item.is_uping?'loading':'over'"></view>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
						<view v-if="item.is_uping==false&&item.remote==null">
							<view @click.stop="retryUpload(item,index)"
								style="position: absolute;z-index: 2;top: 40upx;right: 25upx;">
								<view class="flex justify-center align-center" style="flex-direction: column;">
									<text class="text-white sm">上传失败</text>
									<text class="text-white sm">点击重试</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="flex justify-between align-center padding-bottom padding-top-sm" style="width: 100%;">
				<view class="flex justify-start align-center text-xl text-bold">
					<button :disabled="useAudio" @tap.stop="clickEmoji" class="cu-btn round cuIcon-emoji"></button>
					<view style="width: 20upx;"></view>
					<button @tap.stop="ChooseImage" class="cu-btn round cuIcon-pic"></button>
					<view style="width: 20upx;"></view>
					<button @tap.stop="ChooseAtUser" class="cu-btn round cuIcon-remind"></button>
					<view style="width: 20upx;"></view>
					<button v-if="enableAudioContent==1" @tap.stop="useAudio=!useAudio"
						:class="'cu-btn round cuIcon-'+[useAudio?'keyboard':'voice']"></button>
				</view>
				<view class="flex justify-end align-center">
					<button @tap="commitAction" class="round cu-btn bg-gradual-blue"
						:disabled="disableCommit">{{doneBtn}}</button>
				</view>
			</view>
			<view v-if="showEmojiPanel" class="padding-bottom-xl" style="width: 100%;">
				<emotion @emotion="handleEmotion" :height="emojiPanelHeight" style="width: 100%;"></emotion>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		uploadImage,
		uploadFile,
		createComment,
		replyComment
	} from '@/api/api.js'
	import Emotion from '@/components/Emotion/index.vue'
	import AudioPlayer from '@/components/audio-player.vue'
	import config from '@/api/config.js'
	export default {
		name: "InputPanel",
		components: {
			Emotion,
			AudioPlayer
		},
		data() {
			return {
				enableAudioContent:config.enableAudioContent,
				emojiPanelHeight: 200,
				inputBarBottom: 0,
				commentId: 0,
				postId: 0,
				audioPath: null,
				audioRemote: null,
				durationTimer: null,
				recorderManager: uni.getRecorderManager(),
				show: false,
				modeClass: 'fade',
				duration: 0,
				showDuration:0,
				maxDuration: 30000,
				isRecording: false,
				isStart: false,
				useAudio: false,
				holdMask: false,
				content: '',
				showMask: false,
				foucs: true,
				showEmojiPanel: false,
				imgList: [],
				atUserList: [],
				requestStatus: {
					isAudioChoosed: false,
					isAudioUploading: false,
					isAudioUploadSuccess: false,
					isUpingVideo: false,
					upingVideoSuccess: false
				}
			};
		},
		created() {

			let self = this;
			this.recorderManager.onStop(function(res) {
				console.log('recorder stop' + JSON.stringify(res));
				self.audioPath = res.tempFilePath
				self.finishRecordAudio()
			});
			uni.onKeyboardHeightChange(function(res) {
				console.log(res)
				self.inputBarBottom = res.height
				if (res.height > 0) {
					self.showEmojiPanel = false
					self.emojiPanelHeight = res.height
				}
			})
		},
		computed: {
			disableCommit() {
				if(this.content&&this.content.length>0) {
					return false
				}
				if(this.imgList.length>0) {
					return false
				}
				if(this.audioRemote&&this.audioRemote.length>0) {
					return false
				}
				return true
			},
			maskShow() {
				if (this.holdMask) {
					return true
				}
				return this.showMask
			},
			recordIcon() {
				if (this.isStart == false) {
					return 'voice'
				}
				if (this.isRecording) {
					return 'stop'
				}
				return 'playfill'
			}
		},
		props: {
			title: {
				type: String,
				default: null
			},
			doneBtn: {
				type: String,
				default: null
			},
			autoFocus: {
				type: Boolean,
				default: false
			},
			originInfo: {
				type: Object,
				default: {}
			}
		},
		methods: {
			commitAction() {
				if (this.audioRemote == null && this.content.length == 0 && this.imgList.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '语音，文字，图片内容都为空！'
					})
					return
				}
				let params = {}
				if (this.content.length > 0) {
					params['content'] = this.content
				}
				if (this.audioRemote && this.audioRemote.length > 0) {
					params['audioUrl'] = this.audioRemote
					params['audioDuration'] = this.duration
				}
				if (this.imgList.length > 0) {
					let imgUrlList = []
					this.imgList.forEach(item => {
						imgUrlList.push(item.remote)
					})
					params['imageList'] = imgUrlList
				}
				if (this.originInfo.commentId && this.originInfo.commentId > 0) {
					params['commentId'] = this.originInfo.commentId
					params['postId'] = this.originInfo.postId
					uni.showLoading({
						title: '正在提交...'
					})
					let postIndex = this.originInfo.postIndex 
					replyComment(params).then(res => {
						this.$emit('onReplySuccess',[postIndex,res.data])
						uni.hideLoading()
						uni.showToast({
							title: '回复成功'
						})
						this.clickMask()
					}).catch(error => {
						uni.hideLoading()
					})
					return
				}
				if (this.originInfo.postId && this.originInfo.postId > 0) {
					params['postId'] = this.originInfo.postId
					if(this.originInfo.commentId && this.originInfo.commentId > 0) {
						params['commentId'] = this.originInfo.commentId
					}
					uni.showLoading({
						title: '正在提交...'
					})
					createComment(params).then(res => {
						let postIndex = this.originInfo.postIndex 
						this.$emit('onCommentSuccess',[postIndex,res.data])
						uni.hideLoading()
						uni.showToast({
							title: '评论成功'
						})
						this.clickMask()
					}).catch(error => {
						uni.hideLoading()
					})
				}
			},
			deleteAudio() {
				this.audioPath = null
				this.audioRemote = null
			},
			onGetAudioDuration(duration) {
				console.log('get audio duration', duration)
				this.duration = parseInt(duration)
			},
			finishRecordAudio() {
				this.requestStatus.isAudioChoosed = true
				//上传语音
				let timestamp = new Date().getTime()
				let fileKey = String(timestamp) + '.mp3'
				uploadFile(this.audioPath, fileKey, remoteUrl => {
					this.audioRemote = remoteUrl
					this.requestStatus.isAudioUploading = false
					this.requestStatus.isAudioUploadSuccess = true
				}, error => {
					console.log(error)
					this.requestStatus.isAudioUploading = false
					this.requestStatus.isAudioUploadSuccess = false
				})
			},
			reStart() {
				this.duration = 0
				this.showDuration = 0
				this.recorderManager.start({
					format: 'mp3'
				})
				let that = this
				this.durationTimer = setInterval(() => {
					that.duration += 1
					that.showDuration +=1
				}, 1000)
				this.isStart = true
				this.isRecording = true
			},
			format(num) {
				return '0'.repeat(2 - String(Math.floor(num / 60)).length) + Math.floor(num / 60) + ':' + '0'.repeat(2 -
					String(Math.floor(num % 60)).length) + Math.floor(num % 60)
			},
			startRecord() {
				if (this.isStart) {
					if (this.isRecording) {
						this.recorderManager.pause()
						this.isRecording = false
						clearInterval(this.durationTimer)
					} else {
						this.recorderManager.resume()
						this.isRecording = true
						let that = this
						this.durationTimer = setInterval(() => {
							that.duration += 1
							that.showDuration += 1
						}, 1000)
					}
					return
				}
				this.recorderManager.start({
					format: 'mp3',
					duration: this.maxDuration
				})
				let that = this
				this.durationTimer = setInterval(() => {
					that.duration += 1
					that.showDuration += 1
				}, 1000)
				this.isStart = true
				this.isRecording = true
			},
			saveAction() {
				this.recorderManager.stop()
				clearInterval(this.durationTimer)
				this.isStart = false
				this.isRecording = false
				this.showDuration = 0
			},
			jumpToUserProfile(userId) {
				uni.navigateTo({
					url: '/pages/profile/profile?userId=' + userId
				})
			},
			ChooseAtUser() {
				let that = this
				uni.navigateTo({
					url: '/pages/lessuse/at-user-choose/at-user-choose',
					success(res) {
						res.eventChannel.emit('passUserList', that.atUserList)
					},
					events: {
						finishChoose: function(data) {
							that.atUserList = data
						}
					}
				})
			},
			onTextInputFocus() {
				this.showMask = true
				this.showEmojiPanel = false
				this.foucs = true
				this.holdMask = true
			},
			clickEmoji() {
				console.log('click emoji')
				this.foucs = !this.foucs
				this.showEmojiPanel = !this.showEmojiPanel
				this.holdMask = this.showEmojiPanel
			},
			handleEmotion(i) {
				this.content += i
			},
			clickMask() {
				this.foucs = false
				this.commentId = 0
				this.postId = 0
				this.$emit('blur')
			},
			contentUpdate(e) {
				this.content = e.detail.value
			},
			ChooseImage() {
				if (this.imgList.length >= 4) {
					uni.showToast({
						icon: 'none',
						title: '最多上传四张'
					})
				}
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						let timestamp = new Date().getTime()
						let fileKey = String(timestamp)
						let item = {
							'local': res.tempFilePaths[0],
							'remote': null,
							'is_uping': false,
							'fileKey': fileKey,
						}
						this.imgList.push(item)
						let index = this.imgList.length - 1
						this.imgList[index].is_uping = true
						uploadImage(res.tempFilePaths[0], fileKey, (imgUrl) => {
							console.log(imgUrl)
							this.imgList[index].remote = imgUrl
							this.imgList[index].is_uping = false
						}).catch(error => {
							this.imgList[index].is_uping = false
						})
					}
				});
			},
			ViewCommentImage(e) {
				console.log(e.currentTarget.dataset.list)
				console.log(e.currentTarget.dataset.url)
				uni.previewImage({
					urls: e.currentTarget.dataset.list,
					current: e.currentTarget.dataset.url
				});
			},
			ViewImage(e) {
				console.log(this.imgList)
				console.log(e.currentTarget.dataset.url)
				let previewImgList = []
				this.imgList.forEach(item => {
					previewImgList.push(item.local)
				})
				uni.previewImage({
					urls: previewImgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			retryUpload(item, index) {
				this.imgList[index].is_uping = true
				uploadImage(item.local, item.fileKey, (imgUrl) => {
					console.log(imgUrl)
					this.imgList[index].remote = imgUrl
					this.imgList[index].is_uping = false
				}, (error) => {
					this.imgList[index].is_uping = false
				})
			},
		},
	}
</script>

<style lang="scss">
	.mask-board {
		position: relative;
		height: 100%;
		width: 100%;
		background-color: rgba(0, 0, 0, 0.3);
	}

	.input-area {
		position: relative;
		height: 120upx;
		width: 100%;
	}

	.panel-root {
		position: absolute;
		flex-direction: column;
		top: 0%;
		height: 100%;
		width: 100%;
	}

	.input-bar {
		flex-direction: column;
		position: absolute;
		z-index: 99;
		bottom: 0%;
		width: 100%;
	}
</style>
